/*
 * @Author: sdorein sdorein@163.com
 * @Date: 2024-07-25 17:26:37
 * @LastEditors: sdorein sdorein@163.com
 * @LastEditTime: 2024-07-25 17:28:42
 * @FilePath: \node-ts-project\server\upload.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

async function uploadMiniProgramCode(accessToken, appId, codePath) {
  const formData = new FormData();
  formData.append('appid', appId);
  formData.append('version', '0.0.1'); // 版本号，根据实际需要设置
  formData.append('project.config.json', JSON.stringify({ /* 项目配置 */ }));
  formData.append('app.js', fs.createReadStream(codePath + '/app.js'));
  // 如果有其他文件，如wxml, wxss等，也需要相应添加到formData中

  const headers = {
    ...formData.getHeaders(), // 重要：添加此header以确保正确的Content-Type
    'Authorization': `Bearer ${accessToken}`
  };

  try {
    const response = await axios.post('https://api.weixin.qq.com/wxa/uploadcode', formData, { headers });
    console.log('上传成功', response.data);
  } catch (error) {
    console.error('上传失败', error);
  }
}

// 假设你已经有了access_token和小程序ID
const accessToken = '82_inSNC4xZ0jBOgPp3mvrIPjnYKdG22Lh6ObqcTXwEgo1N06-F6cFTUokGEGV8BMTWHaXab5o7cntmdebqMe6KSc821_h1txOWfYxEOqdbbLzDhZfCQxLw7MzVMT0MGDfABAICZ';
const appId = 'wx70a595fc42f347f0';
const codePath = 'PATH_TO_YOUR_MINIPROGRAM_CODE_DIRECTORY';

uploadMiniProgramCode(accessToken, appId, codePath);